import Icon from '@/components/Icon'
import { NavBar, Input, Toast } from 'antd-mobile'
import { useHistory } from 'react-router-dom'
import styles from './index.module.scss'
import io, { Socket } from 'socket.io-client'
import React, { useEffect, useRef, useState } from 'react'
import { Talk } from '@/types/data'
import { getToken } from '@/utils/storage'

const Chat = () => {
  const history = useHistory()
  const [messageList, setMessageList] = useState<Talk[]>([
    { type: 'zmztya', text: '亲爱的用户您好，小智同学为您服务' },
    { type: 'user', text: '你好' },
  ])
  const [message, setMessage] = useState<string>('')
  const clientRef = useRef<Socket | null>(null)

  const chatListRef = useRef<HTMLDivElement>(null)
  useEffect(() => {
    const client = io('http://toutiao.itheima.net', {
      query: {
        token: getToken().token,
      },
      transports: ['websocket'],
    })
    clientRef.current = client
    client.on('connect', () => {
      Toast.show({
        icon: 'success',
        content: '连接成功',
      })
    })
    client.on('message', function (e: { msg: string; timestamp: number }) {
      console.log('收到消息')
      setMessageList((list) => [...list, { type: 'zmztya', text: e.msg }])
    })

    return () => {
      clientRef.current!.close()
    }
  }, [])

  useEffect(() => {
    const current = chatListRef.current!
    current.scrollTop = current.scrollHeight
  }, [messageList])

  const onSendMessage = (e: React.KeyboardEvent) => {
    if (e.code === 'Enter' && message) {
      clientRef.current!.emit('message', {
        msg: message,
        timestamp: Date.now(),
      })
      setMessageList((list: Talk[]) => {
        return [...list, { type: 'user', text: message }]
      })
      setMessage('')
    }
  }

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar className="fixed-header" onBack={() => history.go(-1)}>
        小智同学
      </NavBar>

      {/* 聊天记录列表 */}

      <div className="chat-list" ref={chatListRef}>
        {messageList.map((item, index): any => {
          if (item.type === 'zmztya') {
            return (
              <div className="chat-item" key={index}>
                <Icon type="iconbtn_xiaozhitongxue" />
                <div className="message">{item.text}</div>
              </div>
            )
          } else {
            return (
              <div className="chat-item user" key={index}>
                <img
                  src={'http://toutiao.itheima.net/images/user_head.jpg'}
                  alt=""
                />
                <div className="message">{item.text}</div>
              </div>
            )
          }
        })}
      </div>

      {/* 底部消息输入框 */}
      <div className="input-footer">
        <Input
          className="no-border input"
          placeholder="请描述您的问题"
          value={message}
          onKeyDown={onSendMessage}
          onChange={(e) => setMessage(e)}
        />
        <Icon type="iconbianji" />
      </div>
    </div>
  )
}

export default Chat
